asynx.namespace("windows.overlay");

asynx.windows.overlay = function() {
	this._init(arguments);
};

asynx.windows.overlay.prototype = {
	
	_init: function(arguments) {
		
		var args = arguments[0] || {};
		
		this.arguments = args;
		
		this.container = asynx('/body');
		
		this.divOverlay = document.createElement("div");
 		
		this.bgOverlay = args.color || "#000";
		
		this.alphaOverlay = args.alpha || 80;
		
		this.fadeEquation = args.fadeEquation || asynx.anim.easing.linear;
		
		this.fadeDuration = args.fadeDuration || 10;
		
		this.fixzIndex = args.fixzIndex == false ? false : true;
		
		this.periodicalRenderInterval = null;
		
		this.onComplete = args.onComplete || args.onLoad;
		
		this.onStart = args.onStart;
		
		this.closeOnClick = args.closeOnClick == false ? false : true;
		
		this.lastPageWidth = 0;
		
		this.lastPageHeight = 0;
		
	},
	
	_createOverlayContainer: function() {
		 if (this.container) {
		 
			 var div = this.divOverlay, scope = this;
			 
			 asynx.dom.append(this.container, div);
			 
			 asynx.disableSelection(div);
			 
			 asynx(div).css({alpha: 0});
			 
			 this._renderOverlayCss();
			 
			 var fadeSettings = {from: 0, to: this.alphaOverlay , duration:this.fadeDuration, equation: this.fadeEquation };
			 
			 asynx.anim.fade(this.divOverlay, fadeSettings, function() {
			 	if (scope.onComplete) scope.onComplete.apply(scope.divOverlay, [scope]);
			 });
			 
			 asynx(div).click(function() {
			 	if (scope.closeOnClick)	scope.hide();
			 });
			 
			this._firePeriodicalRender();
			
		}
	},
	
	_renderOverlayCss: function() {
			
		var div = this.divOverlay, scope = this, pageXY = asynx.getPageSize();
		
		this.lastPageWidth = pageXY[0];
		this.lastPageHeight = pageXY[1]; 
		
		
		asynx(div).css({
		 	position: 'absolute',
			zIndex: 1,
			top: '0px',
			left: '0px',
			bg: this.bgOverlay,
			width: pageXY[0] + "px",
			height: pageXY[1] + "px"
		 });
		 
		if (asynx.isIE && this.fixzIndex) {
			
			if (div && div.zIndexFixer)
				asynx('/body').removeChild(asynx(div.zIndexFixer));
			
		 	asynx.fixzIndex(this.divOverlay);
		}
		 
	},
	
	_firePeriodicalRender: function() {
		
		this.periodicalRenderInterval = asynx.delay(function() {
			
			var pageXY = asynx.getPageSize();
			
			var resized = pageXY[0]!=this.lastPageWidth || pageXY[1]!=this.lastPageHeight;
			
			if (resized) this._renderOverlayCss();
				
		}, 1000, true, this);
	},
	
	show: function() {
		
		if (this.onStart) this.onStart.apply(this.divOverlay, [this]);
		
		this._createOverlayContainer();
		
	},
	
	hide: function() {
		asynx.dom.remove(this.container, this.divOverlay);
		clearInterval(this.periodicalRenderInterval);
	},
	
	addEvent: function(type, fn, args) {
		asynx.event.add(type, this.divOverlay, fn, args);
	}
	
}